package leetcode

import kotlinetc.println

//https://leetcode.com/problems/find-and-replace-pattern/

fun main(args: Array<String>) {

    matchPattern("acc", "abb").println()
}

val patternMap = hashMapOf<Char, Char>()

val wordMap = hashMapOf<Char, Char>()

fun findAndReplacePattern(words: Array<String>, pattern: String): List<String> {

    val result = arrayListOf<String>()
    words.forEach {
        if (matchPattern(it, pattern))
            result.add(it)
    }
    return result
}

fun matchPattern(word: String, pattern: String): Boolean {
    if (word.length != pattern.length) return false
    patternMap.clear()
    wordMap.clear()

    for (i in 0 until word.length) {
        if (patternMap[word[i]] != null) {
            if (patternMap[word[i]] != pattern[i])
                return false
        } else if (wordMap[pattern[i]] != null) {
            if (wordMap[pattern[i]]!= word[i])
                return false
        } else {
            patternMap[word[i]] = pattern[i]
            wordMap[pattern[i]] = word[i]
        }

    }

    return true
}
